import {Form, Input, message, Modal} from 'antd';
import React from 'react';
import type {RegisterFormFields} from '../data';


function checkDuplication<T = any>(arr: T[]) {
  const map: Map<T, any> = new Map();

  const filterdArr: T[] = [];

  const dupIndex: number[] = [];

  arr.forEach((item, index) => {
    if (map.get(item) === true) {
      dupIndex.push(index);
    } else {
      map.set(item, true);
      filterdArr.push(item);
    }
  });
  return dupIndex;
}

interface BindFormProps {
  values?: { deviceNo?: string };
  onSubmit: (values: RegisterFormFields) => void;
  onCancel: (flag?: boolean) => void;
  modalVisible: boolean;
  visibleHandler: (flag?: boolean) => void;

}

const formItemLayout = {
  labelCol: {
    xs: {span: 4},
    sm: {span: 4},
  },
  wrapperCol: {
    xs: {span: 20},
    sm: {span: 20},
  },
};

const BindForm: React.FC<BindFormProps> = props => {
  const [form] = Form.useForm();

  const {
    values: initValues,
    onSubmit: handleAdd,
    onCancel: handleAddModalVisible,
    modalVisible: addModalVisible,
  } = props;

  const onModalOk = async () => {
    const rawFieldsValue = (await form.validateFields()) as {
      deviceNo: string;
    };

    const deviceNoArr = rawFieldsValue.deviceNo.split('\n').filter(v => v);

    const dupIndex = checkDuplication(deviceNoArr);
    if (dupIndex.length > 0) {
      message.error(
          `传入的设备号存在 ${dupIndex.length} 个重复值，建议检查第${dupIndex
          .slice(0, 5)
          .map(i => i + 1)
          .join(', ')} 行`,
      );
      return;
    }

    const fieldsValue = {
      deviceNo: deviceNoArr.length !== 1 ? deviceNoArr : deviceNoArr[0],
    } as RegisterFormFields;

    if (fieldsValue) handleAdd(fieldsValue);
  };

  return (
      <Modal
          title='注册设备'
          visible={addModalVisible}
          destroyOnClose
          onOk={() => onModalOk()}
          onCancel={() => handleAddModalVisible(false)}
          afterClose={() => handleAddModalVisible(false)}
          okText='确定'
          cancelText='取消'
      >
        <Form {...formItemLayout} form={form} initialValues={{...initValues}}>
          <Form.Item name='deviceNo' label='设备编号' rules={[{required: true, message: '必填'}]}>
            <Input placeholder='目前只支持注册第一个设备'/>
          </Form.Item>
        </Form>
      </Modal>
  );
};

export default BindForm;
